﻿using CommonTools;
using shop.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace shop.Bll.cost
{
    public class SpecialPostBll:IPageBll<SpecialPost>
    {
        public string Title => "特殊运费";

        public bool EnableEditOnList => true;

        public bool EnableCreateOnList => true;

        public bool RefreshOnOpen => true;

        public Action<int> TurnPage { set; get; }
        public SpecialPost CopyItem(SpecialPost item)
        {
            if (item == null)
                return null;

            var newItem = item.Clone();
            newItem.id = 0;
            newItem.isdel = false;

            return newItem;
        }

        public SpecialPost CreateItem()
        {
            return new SpecialPost() { isdel = false, FUser = UserBll.CurrentUser.Name, FTime = DateTime.Now,};
        }

        public async Task<Result> DeleteItem(int id)
        {
            await DB.FSql.Update<SpecialPost>()
                .Where(a => a.id == id && a.isdel == false)
                .Set(a => a.isdel, true)
                .ExecuteAffrowsAsync();

            await DB.FSql.Insert(new CLogs()
            {
                DocName = nameof(SpecialPost),
                Computer = UserBll.CurrentUser.ComputerInfo,
                Zdr = UserBll.CurrentUser.Name,
                DocId = id.ToString(),
                DocAction = "删除",
            })
                .ExecuteAffrowsAsync();

            return new Result(true);
        }


        public async Task<Result<int>> EditCell(string dataPropertyName, object value,  SpecialPost data)
        {
            if (data.id == 0)
            {
                data.FTime = await DB.FSql.GetTimeAsync();
                data.FUser = UserBll.CurrentUser.Name;
                data.isdel = false;

                if (dataPropertyName != nameof(data.BeginDate)) data.BeginDate = DateTime.Today;
                if (dataPropertyName != nameof(data.EndDate)) data.EndDate = new DateTime(2099, 1, 1);


                var nid = await DB.FSql.Insert(data)
                    .ExecuteIdentityAsync();

                data.id = (int)nid;
            }

            var dict = new Dictionary<string, object> { [dataPropertyName] = value };



            var dbRes = await DB.FSql.Update<SpecialPost>()
                .Where(a => a.id == data.id && a.isdel == false)
                .SetDto(dict)
                .ExecuteAffrowsAsync();

            return new Result<int>(true, "!", data.id);
        }

        public IEnumerable<DeclareColumn> GetColumns()
        {
            return new[]
            {
                new DeclareColumn(nameof(SpecialPost.id),"id"){ Visible= false},
                new DeclareColumn(nameof(SpecialPost.BeginDate),"起始日期"){ Width=100, ValueType= typeof(DateTime)},
                new DeclareColumn(nameof(SpecialPost.EndDate),"截止日期"){ Width=110 ,ValueType=typeof(DateTime) },
                new DeclareColumn(nameof(SpecialPost.logistics_name),"物流公司"){ Width=220 },
                new DeclareColumn(nameof(SpecialPost.Stock),"仓库"){ Width=260 },
                new DeclareColumn(nameof(SpecialPost.spec_no),"商家编码"){ Width=270},
                new DeclareColumn(nameof(SpecialPost.PostPrice),"运费单价"){ ValueType= typeof(decimal), Width=120},
                new DeclareColumn(nameof(SpecialPost.FUser),"制单人"),
            };
        }

        public async Task<SpecialPost> GetItem(int id)
        {
            return await DB.FSql.Select<SpecialPost>()
                .Where(a => a.isdel == false && a.id == id)
                .ToOneAsync();
        }


        #region 查询参数

        private DateTime? _begin;
        private DateTime? _end;
        private string _stock;
        private string _logistics_name;
        private string _specno;

        #endregion

        /// <summary> 查询ui </summary>
        public virtual ControlBuilder GetUIBuilder()
        {
            return new ControlBuilder()
                .Add<DateTime?>(ControlEnum.gtDatePicker, "起始日期", c => _begin = c)
                .Add<DateTime?>(ControlEnum.gtDatePicker, "截止日期", c => _end = c)
                .Add<string>(ControlEnum.guanTextBox, "仓库", c => _stock= c)
                .Add<string>(ControlEnum.guanTextBox, "物流公司", c => _logistics_name= c)
                .SetFlowBreak()
                .Add<string>(ControlEnum.guanTextBox, "商家编码", c => _specno= c)
                .AddQueryButton("查询");
        }

        /// <summary> 查询 </summary>
        public async Task<PageQueryResult<SpecialPost>> QueryPage(DocFilterParameter queryPara)
        {
            var list = await DB.FSql.Select<SpecialPost>()
                .Where(a => a.isdel == false)
                .WhereIf(_begin != null, a => a.BeginDate <= _begin.Value.Date && a.EndDate >= _begin.Value.Date)
                .WhereIf(_end != null, a => a.BeginDate <= _end.Value.Date && a.EndDate >= _end.Value.Date)
                .WhereIf(!string.IsNullOrEmpty(_stock), a => a.Stock.Contains(_stock))
                .WhereIf(!string.IsNullOrEmpty(_logistics_name), a => a.logistics_name.Contains(_logistics_name))
                .WhereIf(!string.IsNullOrEmpty(_specno), a => a.spec_no.Contains(_specno))
                .Page(queryPara.PageNo, queryPara.PageSize)
                //.OrderByDescending(a => a.shopGroup)
                .OrderBy(a => a.Stock)
                .Count(out var c)
                .ToListAsync();

            return new PageQueryResult<SpecialPost>(true, null, list, c);
        }



        public async Task<Result> SaveItem(SpecialPost item)
        {
            if (item == null)
            {
                return new Result(false, "系统错误");
            }

            string err = string.Empty;
            if (string.IsNullOrEmpty(item.logistics_name))
            {
                err += "物流公司不能为空!";
            }

            if (string.IsNullOrEmpty(err) == false)
            {
                return new Result(false, err);
            }

            item.isdel = false;
            item.FTime = await DB.FSql.GetTimeAsync();
            item.FUser = UserBll.CurrentUser.Name;

            if (item.id <= 0)
            {
                var id = await DB.FSql.Insert(item)
                    .ExecuteIdentityAsync();

                item.id = (int)id;
            }
            else
            {
                await DB.FSql.Update<SpecialPost>()
                    .SetSource(item)
                    .ExecuteAffrowsAsync();
            }

            return new Result(true);
        }


        public async Task<Result> SaveItem(IEnumerable<SpecialPost> items)
        {
            if (items == null)
            {
                return new Result(false, "系统错误");
            }

            var time = await DB.FSql.GetTimeAsync(); 

            foreach (var item in items)
            {
                item.isdel = false;
                item.FTime = time;
                item.FUser = UserBll.CurrentUser.Name;
            }

            await DB.FSql.Insert(items).ExecuteAffrowsAsync();

            return new Result(true);

        }


    }
}
